package com.gupaoedu.chat.client;

import com.gupaoedu.chat.client.handler.ChatClientHandler;
import com.gupaoedu.chat.protocol.IMDecoder;
import com.gupaoedu.chat.protocol.IMEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Created by ASUS on 2017/10/21.
 */
public class ChatClient {
    String host;
    int port;
    ChatClientHandler chatClientHandler;

    /**
     * 初始化自己的客户端的Handler
     * @param nickName
     */
    public ChatClient(String nickName) {
        chatClientHandler=new ChatClientHandler(nickName);
    }

    /**
     * 进行连接服务器
     */
    public void connect(String host, int port) {
        this.host=host;
        this.port=port;

        EventLoopGroup workGroup=new NioEventLoopGroup();
        Bootstrap b=new Bootstrap();
        try {
            //客户端与服务端保持长连接
            b.group(workGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE,true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    //先解码
                    socketChannel.pipeline().addLast(new IMDecoder());
                    //后编码
                    socketChannel.pipeline().addLast(new IMEncoder());
                    //植入自己的clientHandler
                    socketChannel.pipeline().addLast(chatClientHandler);
                }
            });
            //连接服务端 异步操作
            ChannelFuture future = b.connect(host, port).sync();
            //通道关闭任务,异步
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
            workGroup.shutdownGracefully();
        }

    }
    public static void main(String[] args) {
       new ChatClient("zhangyang").connect("127.0.0.1",8080);
    }
}
